Return an Array in C
What is an Array?
An array is a type of data structure that stores a fixed-size of a homogeneous collection of data. In short, we can say that array is a collection of variables of the same type.For example, if we want to declare 'n' number of variables, n1, n2...n., if we create all these variables individually, then it becomes a very tedious task. In such a case, we create an array of variables having the same type. Each element of an array can be accessed using an index of the element.
Let's first see how to pass a single-dimensional array to a function.
Passing array to a function.
#include
void getarray(int arr[])
{
printf("Elements of array are : ");
for(int i=0;i<5;i++)
{
printf("%d ", arr[i]);
}
}
int main()
{
int arr[5]={45,67,34,78,90};
getarray(arr);
return 0;
}
Output
Now, we will see how to pass an array to a function as a pointer.
#include
void printarray(char *arr)
{
printf("Elements of array are : ");
for(int i=0;i<5;i++)
{
printf("%c ", arr[i]);
}
}
int main()
{
char arr[5]={'A','B','C','D','E'};
printarray(arr);
return 0;
}
Output
Returning pointer pointing to the array
#include
int *getarray()
{
int arr[5];
printf("Enter the elements in an array : ");
for(int i=0;i<5;i++)
{
scanf("%d", &arr[i]);
}
return arr;
}
int main()
{
int *n;
n=getarray();
printf("nElements of array are :");
for(int i=0;i<5;i++)
{
printf("%d", n[i]);
}
return 0;
}
Output
- Using dynamically allocated array
- Using static array
- Using structure
#include
int *getarray(int *a)
{
printf("Enter the elements in an array : ");
for(int i=0;i<5;i++)
{
scanf("%d", &a[i]);
}
return a;
}
int main()
{
int *n;
int a[5];
n=getarray(a);
printf("nElements of array are :");
for(int i=0;i<5;i++)
{
printf("%d", n[i]);
}
return 0;
}
Output
#include
#include
int *getarray()
{
int size;
printf("Enter the size of the array : ");
scanf("%d",&size);
int *p= malloc(sizeof(size));
printf("nEnter the elements in an array");
for(int i=0;i
Output
#include
int *getarray()
{
static int arr[7];
printf("Enter the elements in an array : ");
for(int i=0;i<7;i++)
{
scanf("%d",&arr[i]);
}
return arr;
}
int main()
{
int *ptr;
ptr=getarray();
printf("nElements that you have entered are :");
for(int i=0;i<7;i++)
{
printf("%d ", ptr[i]);
}
}
Output
Using Structure
The structure is a user-defined data type that can contain a collection of items of different types. Now, we will create a program that returns an array by using structure.
#include
#include
struct array
{
int arr[8];
};
struct array getarray()
{
struct array y;
printf("Enter the elements in an array : ");
for(int i=0;i<8;i++)
{
scanf("%d",&y.arr[i]);
}
return y;
}
int main()
{
struct array x=getarray();
printf("Elements that you have entered are :");
for(int i=0;x.arr[i]!='0';i++)
{
printf("%d ", x.arr[i]);
}
return 0;
}